package com.zxmc.aop;

import com.zxmc.common.utils.BloomFilterUtil;
import com.zxmc.pojo.dto.NovelDto;
import com.zxmc.pojo.dto.NovelQueryDto;
import com.zxmc.pojo.dto.PageNovelQueryDto;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class BloomFilterAspect {

    @Autowired
    private BloomFilterUtil bloomFilterUtil;

    @Around("@annotation(BloomFilterCheck)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        BloomFilterCheck bloomFilterCheck = method.getAnnotation(BloomFilterCheck.class);
        String filterName = bloomFilterCheck.value();


        Object[] args = joinPoint.getArgs();
        if (args.length > 0) {
            String key=getKey(args);
            if (!bloomFilterUtil.mightContain(key)) {
                System.out.println("过滤不存在的key: " + key + " 不执行方法");
                return null; // 如果布隆过滤器判断不存在，直接返回 null
            }

        }
        return joinPoint.proceed();
    }

    public static String getKey(Object[] args) {
        Object arg = args[0];
        String key=null;
        if (arg instanceof Integer) {
            key = "chapter"+arg;
        }else if(arg instanceof NovelQueryDto) {
            key = "novel"+((NovelQueryDto) arg).getId();
        }else if(arg instanceof PageNovelQueryDto) {
            key = "novel"+((PageNovelQueryDto) arg).getId();
        }
        return key;
    }
}
